package mutation;

import java.util.*;

import GA.*;
import Operations.Operation;
import Operations.ValuesGenerator;
import util.*;


public class InsertRandomMethodCall extends MutationStrategy {

	@Override
	public Chromosome mutate( Chromosome individual) {
		List<Operation> ops= individual.getTest();
		try {
			Map<String, Class<?>> cluster= gaInfo.getTestCluster().getCluster();
			Map<String, String[]>  refFactory=gaInfo.getTestCluster().getRefFactory();
			Map<String, MethodDeclared[]> methodsToTest= gaInfo.getTestCluster().getMethodsToTest();
			
			Set<Class<?>> classToTest= gaInfo.getTestCluster().getClassToTest();
			List<Class<?>> clazzUTest = new ArrayList<Class<?>>(new ArrayList<Class<?>>(classToTest));   
			Class<?> cut = clazzUTest.get(ValuesGenerator.getRandomInt(classToTest.size()));
			String cName=cut.getName();

			int randPos = ValuesGenerator.getRandomInt(ops.size());
			List<Operation>  rep= new LinkedList<Operation>();
			rep.addAll(ops.subList(0, randPos));
			int numOfMethods=ValuesGenerator.getRandomIntBetween(1, 10);
			for(int i=1;i<=numOfMethods;i++)
				rep.add( Operation.invokeMethod(cName, cluster, refFactory,methodsToTest));
	
			rep.addAll(ops.subList(randPos, ops.size()));
			individual.setTest(rep);
			return individual;
		} catch (Throwable e){
			System.err.println("Insert Random Method Call Class:" + e.getMessage());
		}	

		
		return null;
		
	}

	@Override
	public boolean getMutationFlag() {
		
		if(ValuesGenerator.getBoleean( GAConfig.mutationRate))
			return true;
		return false;

	}
}
